import {
    Component,
    ElementRef,
    EventEmitter,
    Injector,
    Output,
    ViewChild,
} from "@angular/core";
import { AppComponentBase } from "@shared/common/app-component-base";
import {
    PlacesServiceProxy,
    UserPlaceListDto,
    ParkingsBillingSchemeServiceProxy,
    ParkingsBillingSchemeListDto,
    ComboboxItemDto,
    PlaceEditDto,
    GetPlaceForEditOutput,
    UpdatePlace,
    PaymethodServiceProxy,
    CreatePaymethodDto,
    SetUserParkingInput
} from "@shared/service-proxies/service-proxies";
import { id } from "@swimlane/ngx-charts/release/utils";
import { ModalDirective } from "ngx-bootstrap";
import * as moment from "moment";
import { finalize } from "rxjs/operators";
import { Data } from "@angular/router";
import { result } from "lodash";
import {AppConsts} from "../../../shared/AppConsts"

@Component({
    selector: "createOrEditUserPlaceModal",
    templateUrl: "./create-or-edit-user-place-modal.component.html",
})
export class CreateOrEditUserPlaceModalComponent extends AppComponentBase {
    @ViewChild("createOrEditModal") modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;
    parkingid: number;
    monthlyRentPrice: number;
    quarterlyPrice: number;
    halfYearPrice: number;
    yearPrice: number;
    SellingPrice: number;
    payTypes: ComboboxItemDto[] = [];
    payTypeDisplayText:any;

    places: ComboboxItemDto[] = [];
    emptyText = "";
    payvalue: string;
    newDate: Date;
    etime = new Date();
    userid: number;
    checked2 = true;
    checked = false;
    placeid: number;
    carNum: string;
    carType: string;
    carInfo: string;
    getPlaceForEditOutput: GetPlaceForEditOutput = new GetPlaceForEditOutput();
    PlaceEdit: PlaceEditDto = new PlaceEditDto();
    setUserParking: SetUserParkingInput = new SetUserParkingInput();
    startDate:Date =new Date();
    endDate:Date;
    ch = {
        firstDayOfWeek: 0,
        dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
        dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
        dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
        monthNames: [
            '一月',
            '二月',
            '三月',
            '四月',
            '五月',
            '六月',
            '七月',
            '八月',
            '九月',
            '十月',
            '十一月',
            '十二月'
        ],
        monthNamesShort: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
        today: '今天',
        clear: '清除',
        dateFormat: 'yy-mm-dd'
    };

    LicenseColors = AppConsts.LicenseColors;
    constructor(
        injector: Injector,
        private _placesServiceProxy: PlacesServiceProxy,
        private _parkingsBillingSchemeServiceProxy: ParkingsBillingSchemeServiceProxy,
        private _paymethodServiceProxy: PaymethodServiceProxy
    ) {
        super(injector);
    }
    ngOnInit() {
        this.carType = this.LicenseColors[0].key;
    }
    show(userId: number, parkingid: number): void {
        const self = this;
        self.active = true;
        console.log(userId);
        console.log(parkingid);
        this.parkingid = parkingid;
        this.userid = userId;
        console.log(this.parkingid);
        console.log(this.etime);
        this._parkingsBillingSchemeServiceProxy
            .getAll(this.parkingid,true, "", 0, 200)
            .subscribe((result) => {
                console.log(result.items[0]);
                //  this.billingScheme = result.items[0];
                (this.monthlyRentPrice = result.items[0].monthlyRentPrice),
                    (this.quarterlyPrice = result.items[0].quarterlyPrice),
                    (this.halfYearPrice = result.items[0].halfYearPrice),
                    (this.yearPrice = result.items[0].yearPrice);
                this.SellingPrice = result.items[0].sellingPrice;
                if (this.payTypes.length == 0) {
                    let monthlyRentPrice = new ComboboxItemDto();
                    (monthlyRentPrice.displayText =
                        "月付" + this.monthlyRentPrice + "元/月"),
                        (monthlyRentPrice.value =
                            this.monthlyRentPrice.toString()),
                        this.payTypes.push(monthlyRentPrice);

                    let quarterlyPrice = new ComboboxItemDto();
                    (quarterlyPrice.displayText =
                        "季付" + this.quarterlyPrice + "元/月"),
                        (quarterlyPrice.value = (
                            this.quarterlyPrice * 3
                        ).toString()),
                        this.payTypes.push(quarterlyPrice);
                    let halfYearPrice = new ComboboxItemDto();
                    (halfYearPrice.displayText =
                        "半年付" + this.halfYearPrice + "元/月"),
                        (halfYearPrice.value = (
                            this.halfYearPrice * 6
                        ).toString()),
                        this.payTypes.push(halfYearPrice);

                    let yearPrice = new ComboboxItemDto();
                    yearPrice.displayText = "年付" + this.yearPrice + "元/月";
                    (yearPrice.value = (this.yearPrice * 12).toString()),
                        this.payTypes.push(yearPrice);
                }

                console.log(this.payTypes);
                console.log(this.etime);
            });

        this._placesServiceProxy.getComboxForPlaces().subscribe((result) => {
            this.places = result.items;
        });
        self.modal.show();
    }

    onShown(): void {}

    save(): void {
        const self = this;
        let setUserParking = new SetUserParkingInput();
        let month = 0;
        if (Number(this.payvalue) == this.monthlyRentPrice) {
            month = 1;
        }
        if (Number(this.payvalue) == this.quarterlyPrice * 3) {
            month = 3;
        }
        if (Number(this.payvalue) == this.halfYearPrice * 6) {
            month = 6;
        }
        if (Number(this.payvalue) == this.yearPrice * 12) {
            month = 12;
        }

        let etime = this.etime
            ? moment(this.etime).add(month, "months")
            : undefined;

        setUserParking.cycle = month;

        setUserParking.cost =
            this.checked2 == true
                ? Number(this.payvalue)
                : Number(this.SellingPrice);
        setUserParking.carNum = this.carNum;
        setUserParking.carInfo = this.carInfo;
        setUserParking.carType = this.carType;
        setUserParking.checked2 = this.checked2;
        setUserParking.checked = this.checked;
        setUserParking.placesId = this.placeid;
        setUserParking.userId = this.userid;
        // setUserParking.etime =
        //     this.checked2 == true
        //         ? moment(this.etime).add(month, "months")
        //         : moment(this.etime).add(50, "years");
        setUserParking.sTime = moment(this.startDate);
        setUserParking.etime = moment(this.endDate);

        this._placesServiceProxy
            .setUserParkings(setUserParking)
            .subscribe(() => {
                this.notify.info(this.l("SavedSuccessfully"));
                this.close();
                this.modalSave.emit(null);
            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
    getParkingsBillingScheme() {}

    payTypeChange(e:any){
        var payType = this.payTypes.filter(e=>e.displayText == this.payTypeDisplayText);
        if(payType.length == 0){
            this.payvalue = "";
        }else{
            this.payvalue = payType[0].value;
        }
        this.setEndTime();
    }

    setEndTime(){        
        if(this.checked2 == true)   {
            var payType = this.payTypes.filter(e=>e.displayText == this.payTypeDisplayText);
            if(payType.length == 0){
                this.endDate = null;
                return;
            }
            
            let payTypeStart= payType[0].displayText.substring(0,1);
            if(this.startDate == undefined || this.startDate == null){
                this.endDate = null;
                return;
            }        
            switch(payTypeStart){
                case "月":
                    this.endDate = moment(this.startDate).add(1,'M').add(-1,'d').toDate();
                    break;
                case "季":
                    this.endDate = moment(this.startDate).add(3,'M').add(-1,'d').toDate();
                    break;
                case "半":
                    this.endDate = moment(this.startDate).add(6,'M').add(-1,'d').toDate();
                    break;
                case "年":
                    this.endDate = moment(this.startDate).add(1,'y').add(-1,'d').toDate();
                    break;
                default:
                    this.endDate = null;
                    break;
            }
        }else{
            if(this.startDate == undefined || this.startDate == null){
                this.endDate = null;
                return;
            }   
            this.endDate = moment(this.startDate).add(50,'y').add(-1,'d').toDate();
        }
    }
}
